package com.soft.javase.day14.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/5/24
 */
public class ChatServer {
    private static Map<Socket, PrintWriter> clientMap = new HashMap<>();

    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        try (
                ServerSocket ss = new ServerSocket(9999)
        ) {
            System.out.println("聊天服务器已启动，等待客户端接入...");
            while (true) {
                Socket cs = ss.accept();
                PrintWriter pw = new PrintWriter(cs.getOutputStream(), true);
                clientMap.put(cs, pw);
                System.out.println("新客户端连接: " + cs.getRemoteSocketAddress());
                pool.execute(() -> handleClient(cs));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket cs) {
        try (
                BufferedReader br = new BufferedReader(new InputStreamReader(cs.getInputStream()))
        ) {
            String message;
            while ((message = br.readLine()) != null) {
                if (message.equalsIgnoreCase("bye")) {
                    System.out.println(cs.getRemoteSocketAddress()+"已下线");
                    clientMap.remove(cs);
                    break;
                }
                broadcast(message, cs);
            }
        } catch (IOException e) {
            System.out.println(cs.getRemoteSocketAddress()+"已下线");
            clientMap.remove(cs);
        }
    }

    private static void broadcast(String message, Socket es) {
        clientMap.forEach((socket, writer) -> {
            if (!socket.isClosed() && socket != es) {
                writer.println(message);
            }
        });
    }
}
